﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using YJKRevitDimensionText.OneKeyPlanDim.DimData;
using YJKRevitDimensionText.OneKeyPlanDim.LevelDim;

namespace YJKRevitDimensionText.OneKeyPlanDim.Utility
{
	public class Room2RoomTag
	{
		public static Room2RoomTag GetInstance()
		{
			if (Room2RoomTag.m_Instance == null)
			{
				Room2RoomTag.m_Instance = new Room2RoomTag();
			}
			return Room2RoomTag.m_Instance;
		}

		public static void SetInstanceToNull()
		{
			Room2RoomTag.m_Instance = null;
		}

		private Room2RoomTag()
		{
			this.m_dicLstRoomTag = new Dictionary<ElementId, List<RoomTag>>();
		}

		public List<RoomTag> GetLstRoomTagInRoom(Room room)
		{
			List<RoomTag> result = new List<RoomTag>();
			if (room == null)
			{
				return result;
			}
			if (this.m_dicLstRoomTag.ContainsKey(room.Id))
			{
				result = this.m_dicLstRoomTag[room.Id];
			}
			return result;
		}

		public void SetRoomData(List<Room> lstRoom, Autodesk.Revit.DB.Document doc)
		{
			this.m_lstRoom = lstRoom;
			this.m_doc = doc;
			this.ClassifyRoomAndRoomTag();
		}

		private bool GetAllRoomTag(Autodesk.Revit.DB.Document doc, ref List<RoomTag> lstRoomTag)
		{
			bool result;
			try
			{
				FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
				filteredElementCollector.OfCategory(BuiltInCategory.OST_RoomTags).WhereElementIsNotElementType();
				foreach (Element element in filteredElementCollector)
				{
					RoomTag roomTag = element as RoomTag;
					if (roomTag != null)
					{
						lstRoomTag.Add(roomTag);
					}
				}
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private void ClassifyRoomAndRoomTag()
		{
			if (!this.GetAllRoomTag(this.m_doc, ref this.m_lstRoomTag))
			{
				return;
			}
			foreach (Room room in this.m_lstRoom)
			{
				if (room != null)
				{
					DbRoom item = new DbRoom(room);
					KeyComponent.GetInstance().m_AllRoom.Add(item);
					List<RoomTag> value = new List<RoomTag>();
					this.m_dicLstRoomTag[room.Id] = value;
				}
			}
			foreach (RoomTag roomTag in this.m_lstRoomTag)
			{
				if (roomTag != null)
				{
					Room room2 = roomTag.Room;
					if (room2 != null && this.m_dicLstRoomTag.ContainsKey(room2.Id))
					{
						string name = roomTag.Document.ActiveView.Name;
						string name2 = roomTag.View.Name;
						if (name.Equals(name2))
						{
							this.m_dicLstRoomTag[room2.Id].Add(roomTag);
						}
					}
				}
			}
		}

		private static Room2RoomTag m_Instance;

		private List<Room> m_lstRoom = new List<Room>();

		private Document m_doc;

		private List<RoomTag> m_lstRoomTag = new List<RoomTag>();

		private Dictionary<ElementId, List<RoomTag>> m_dicLstRoomTag = new Dictionary<ElementId, List<RoomTag>>();
	}
}
